import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/home.vue";

Vue.use(VueRouter);

let routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
    redirect: "/member",
    meta: {
      title: "主页",
      keepAlive: true,
    },
  },
  {
    path: "/404",
    name: "404",
    component: () => import("@/views/404.vue"),
    meta: {
      title: "404",
      keepAlive: true,
    },
  },
];

//自动生成路由的方法
const routerContext = require.context("./", true, /\.js$/); //把js文件里面的内容读取出来。本质上是一个webpack content 可以用来扩展文件
routerContext.keys().forEach((route) => {
  // 如果是根目录的 index.js 、不处理
  if (route.startsWith("./index")) {
    return;
  }
  const routerModule = routerContext(route);
  /**
   * 兼容 import export 和 require module.export 两种规范
   */
  routes = routes.concat(routerModule.default || routerModule);
});

// 页面不存在就跳转到404页面
routes = routes.concat({
  path: "*",
  redirect: "/404",
});

// 初始化路由，生成router实例
const router = new VueRouter({
  mode: "history",
  base: process.env.VUE_APP_PATH,
  scrollBehavior(to, from, savedPosition) {
    // keep-alive 返回缓存页面后记录浏览位置
    if (savedPosition && to.meta.keepAlive) {
      return savedPosition;
    }
    // 异步滚动操作
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({ x: 0, y: 1 });
      }, 0);
    });
  },
  routes,
});

export default router;
